<template>
    <div>
        <el-card class="box-card" style="margin-bottom: 10px;">
            <div slot="header" class="clearfix">
                <span style="font-size: large;">撰写文章</span>
            </div>

            <el-row :gutter="5">
                <el-col :span="21">
                    <el-input placeholder="请输入文章标题" v-model="title" style="margin-top: 20px;"></el-input>
                </el-col>
                <el-col :span="3">
                    <el-button style="border-radius: 20px ;margin-left: 20px;margin-bottom: 20px;margin-top: 20px;"
                        type="primary" @click="handleAdd">发布文章</el-button>
                </el-col>
            </el-row>
        </el-card>

        <div class="container">
            <el-form label-width="80px" size="small">
                <mavon-editor ref="mavonEditorRef" v-model="content" :ishljs="true" @imgAdd="imgAdd" />
            </el-form>
        </div>
    </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { reqGetById, reqUpdate } from '@/api/mis/article';
import { ElMessage } from 'element-plus'
// 获取当前路由
const route = useRoute()
let form = reactive({
    content: '',
    title: ''
});

const articleId = route.query.articleId
const articleTitle = ref('');
const content = ref('');
const title = ref('');
const mavonEditorRef = ref(null);

// 在组件挂载后访问mavonEditorRef
onMounted(async () => {
    if (mavonEditorRef.value) {
        // console.log(mavonEditorRef.value); // 这里你可以安全地访问组件实例
    }
    articleTitle.value = (route.params.title as string[])?.[0] || '';
    content.value = (route.params.content as string[])?.[0] || '';
    if (articleId) {
        getInfoById()
    }


});

const getInfoById = async () => {
    let result: any
    result = await reqGetById(articleId)
    if (result.code == 0) {
        content.value = result.data.content
        title.value = result.data.title

    }
}
const handleAdd = async () => {
    const update = {
        content: content.value,
        title: title.value,
        id: Number(articleId)
    }
    const result = await reqUpdate(update)
    if (result.code == 0) {
        ElMessage({ type: 'success', message: '编辑成功！' })
    } else {
        ElMessage({ type: 'error', message: '编辑失败！' })
    }
}

const imgAdd = (pos: any, $file: any) => {
    const formData = new FormData();
    formData.append("file", $file);
};
</script>

<style scoped lang="scss">
.container {
    height: 500px;
}
</style>